package de.reminder.client;

import java.util.List;

import com.google.gwt.core.client.*;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

import de.reminder.client.event.InitializedEvent;
import de.reminder.client.service.FacebookGraphAPIService;
import de.reminder.client.service.FacebookGraphAPIServiceAsync;
import de.reminder.client.widgets.*;
import de.reminder.shared.model.FacebookUser;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class MySimpleReminder implements EntryPoint {

	private final FacebookGraphAPIServiceAsync facebookGraphService = GWT.create(FacebookGraphAPIService.class);
	private String accessToken;
	public static FacebookUser currentUser;
	
	public static final SimpleEventBus eventBus = new SimpleEventBus();
	
	private static MySimpleReminder instance;
	
	public static MySimpleReminder getInstance(){
		return instance;
	}
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		instance = this;
		
		//RootPanel.get().add(new ReminderStack());
		//RootPanel.get().add(new ReminderView());
		//getAccessToken();
		RootPanel.get().add(new Mainframe());
	}
	
	public native void getAccessToken()/*-{
		var obj = this;
		$wnd.FB.login(function (response) {	
			if (response.session) {
				var userID = response.session.uid;
				obj.@de.reminder.client.MySimpleReminder::accessToken = response.session.access_token;
				$wnd.FB.api('/me', function(response) {
					obj.@de.reminder.client.MySimpleReminder::initializeUser(Ljava/lang/String;Ljava/lang/String;)(userID,response.name)
				});
			} else {
				alert('User is logged out');
			}
		},{perms:'read_stream,publish_stream,offline_access'});
	}-*/;
	
	private void initializeUser(String id,String name){
		currentUser = new FacebookUser(id, name);
		facebookGraphService.getFriends(currentUser, accessToken, new AsyncCallback<List<FacebookUser>>() {
			@Override
			public void onSuccess(List<FacebookUser> result) {
				System.out.println("Success get friends");
				currentUser.setFriends(result);
				EditUsers.onInitialized();
				eventBus.fireEvent(new InitializedEvent());
			}
			@Override
			public void onFailure(Throwable caught) {
				System.err.println("Error: get friends of " + currentUser.getName() + " ("+currentUser.getId()+")");
			}
		});
	}
}
